//
//  YCURLResponse.swift
//  YCNetworking
//
//  Created by YC on 2017/3/1.
//  Copyright © 2017年 YC. All rights reserved. mail:yangchong364@qq.com
//

import UIKit

public enum YCURLResponseStatus: Int {
    case success
    case errorTimeout
    case errorNoNetwork
};

public class YCURLResponse {
    private(set) var status: YCURLResponseStatus = .success
    private(set) var contentString: String = ""
    private(set) var content: Any!
    private(set) var requestId: Int = 0
    private(set) var request: URLRequest!
    private(set) var responseData: Data!
    private(set) var isCache: Bool = false
    
    init(responseString: String, requestId: Int, request: URLRequest, responseData: Data!, status: YCURLResponseStatus) {
        self.contentString = responseString
        self.status = status
        self.requestId = requestId
        self.request = request
        self.responseData = responseData
        self.isCache = false
        
        if responseData != nil {
            do {
                try self.content = JSONSerialization.jsonObject(with: responseData, options: .allowFragments)
            } catch {
                NSLog("\(error)")
            }
        }else {
            self.content = nil
        }
    }
    
    init(responseString: String, requestId: Int, request: URLRequest, responseData: Data!, error: NSError!) {
        self.contentString = responseString
        self.status = self.responseStatus(with: error)
        self.requestId = requestId
        self.request = request
        self.responseData = responseData
        self.isCache = false
        
        if responseData != nil {
            do {
                try self.content = JSONSerialization.jsonObject(with: responseData, options: .allowFragments)
            } catch {
                NSLog("\(error)")
            }
        }else {
            self.content = nil
        }
        
    }
    
    // 使用initWithData的response，它的isCache是YES，上面两个函数生成的response的isCache是NO
    init(with data: Data) {
        self.contentString = String(data: data, encoding: .utf8)!
        self.status = self.responseStatus(with: nil)
        self.requestId = 0
        self.request = nil
        self.responseData = data
        do {
            try self.content = JSONSerialization.jsonObject(with: data, options: .allowFragments)
        } catch {
            NSLog("\(error)")
        }
        
        self.isCache = true
    }
    
    
    private func responseStatus(with error: NSError!) -> YCURLResponseStatus {
        if error != nil {
            var result = YCURLResponseStatus.errorNoNetwork
            
            if error.code == YCURLResponseStatus.errorTimeout.rawValue {
                result = .errorTimeout
            }
            
            return result
        }else{
            return YCURLResponseStatus.success
        }
    }
}
